using System;
using System.Collections.Generic;
using OneDayModel.Interfaces;
using OneDayModel.Model;

namespace OneDayModel.Model
{
    public class NewUserProfileModel : INewUserProfileModel
    {
        private Roles roles;
        private readonly IRepository repository;

        public NewUserProfileModel(IRepository repository)
        {
            this.repository = repository;
        }

        public string[] Roles
        {
            get
            {
                IList<IRole> rawRoles = repository.GetRoles();
                roles = new Roles(rawRoles);
                return roles.ToStringArray();
            }
        }

        public IAttributesBuilder NewAttributesBuilder()
        {
            return roles.NewAttributesBuilder();
        }

        public void CreateAndSaveNewUser(string[] userRoles, IAttributeRecord[] attributes)
        {
            IUser user = repository.NewUser();
            foreach (string userRole in userRoles)
            {
                string sRole = userRole;
                do
                {
                    IRole role = roles[sRole];
                    user.AssignRole(role);
                    sRole = role.Parent;
                } while (!string.IsNullOrEmpty(sRole));
            }
            user.SetAttributes(attributes);
            user.Create();
        }

        public bool IsAliasUnique(string alias)
        {
            return repository.IsAliasUnique(alias);
        }

        public AccountStatus GetAccountStatus(string email)
        {
            IUser user = repository.GetUserByEmail(email);
            if (user == null)
                return AccountStatus.notExist;

            AccountStatus accountStatus = (AccountStatus) Enum.Parse(typeof(AccountStatus), user["AccountStatus"]);

            return accountStatus;
        }
    }
}